package oss

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"tdy-backend/global"
)

type Oss struct {
	Client *oss.Client
}

func NewOss() *Oss {
	instance := &Oss{}
	return instance.SetConfig()
}
func (o *Oss) Upload(filepath string, filename string) (string, error) {
	logger := global.TYD_LOGGER
	bucket, err := o.Client.Bucket(global.TYD_CONFIG.GetString("file.config.bucket"))
	if err != nil {
		logger.Error(err.Error())
	}
	err = bucket.PutObjectFromFile(filename, filepath)
	if err != nil {
		logger.Error(err.Error())
	}
	return filename, nil
}

func (o *Oss) SetConfig() *Oss {
	accessKey := global.TYD_CONFIG.GetString("file.config.ak")
	secretKey := global.TYD_CONFIG.GetString("file.config.sk")
	endpoint := global.TYD_CONFIG.GetString("file.config.ep")
	logger := global.TYD_LOGGER
	client, err := oss.New(endpoint, accessKey, secretKey)
	if err != nil {
		logger.Error(err.Error())
	}
	o.Client = client
	return o
}

func (o *Oss) GetUrl(key string) string {
	domain := global.TYD_CONFIG.GetString("file.config.domain")
	return domain + key
}
